import pandas as pd
from scipy.stats import pearsonr

def load_local_metrics(file_path):
    """从本地CSV文件加载metrics数据"""
    try:
        # 读取CSV文件
        df = pd.read_csv(file_path)

        # 检查必要的列是否存在
        required_columns = ['match_score', 'satisfaction', 'clicked']
        missing_columns = [col for col in required_columns if col not in df.columns]

        if missing_columns:
            print(f"错误：CSV文件缺少必要的列：{', '.join(missing_columns)}")
            return None

        # 转换为字典列表（保持与原代码数据格式一致）
        metrics_data = df.to_dict('records')
        print(f"成功从 {file_path} 加载 {len(metrics_data)} 条metrics数据")
        return metrics_data

    except FileNotFoundError:
        print(f"错误：未找到文件 {file_path}")
        return None
    except Exception as e:
        print(f"加载数据时出错：{str(e)}")
        return None


def calculate_correlations(metrics_data):
    """计算各项指标的皮尔逊相关系数"""
    match_scores = [item['match_score'] for item in metrics_data]
    satisfaction_scores = [item['satisfaction'] for item in metrics_data]
    clicked_flags = [item['clicked'] for item in metrics_data]

    if len(match_scores) < 2:
        print("数据不足，无法计算相关性")
        return None

    corr_match_sat, p_match = pearsonr(match_scores, satisfaction_scores)
    corr_click_sat, p_click = pearsonr(clicked_flags, satisfaction_scores)

    return {
        'match_satisfaction': {
            'correlation': round(corr_match_sat, 3),
            'p_value': round(p_match, 3)
        },
        'click_satisfaction': {
            'correlation': round(corr_click_sat, 3),
            'p_value': round(p_click, 3)
        }
    }


def print_correlation_results(results):
    """打印相关系数结果"""
    if not results:
        return

    print("\n=== 皮尔逊相关系数分析结果 ===")

    # 语义匹配度与情感满意度
    match_corr = round(results['match_satisfaction']['correlation'], 3)
    match_p = round(results['match_satisfaction']['p_value'], 3)
    print(f"1. 语义匹配度与情感满意度：")
    print(f"   相关系数：{match_corr}（p值：{match_p}）")
    print(
        f"   解释：{'显著正相关' if match_corr > 0.3 and match_p < 0.05 else '无显著相关' if match_p >= 0.05 else '显著负相关'}\n")

    # 点击行为与情感满意度
    click_corr = round(results['click_satisfaction']['correlation'], 3)
    click_p = round(results['click_satisfaction']['p_value'], 3)
    print(f"2. 点击行为与情感满意度：")
    print(f"   相关系数：{click_corr}（p值：{click_p}）")
    print(
        f"   解释：{'显著正相关' if click_corr > 0.3 and click_p < 0.05 else '无显著相关' if click_p >= 0.05 else '显著负相关'}")


# 主函数
def main():
    # 本地metrics数据文件路径（请根据实际文件位置修改）
    metrics_file_path = ("recommendation_results/topn_clicks_with_metrics.csv")

    # 加载本地数据
    metrics_data = load_local_metrics(metrics_file_path)
    if not metrics_data:
        return  # 加载失败则退出

    # 计算相关系数
    correlation_results = calculate_correlations(metrics_data)

    # 打印结果
    print_correlation_results(correlation_results)


if __name__ == "__main__":
    main()
